import { ILoginParams, login } from "@/api/userApi";
import { Button, Form, Input, message } from "antd";
import { useNavigate } from "react-router-dom";

export const Login: React.FC = () => {
  const navigate = useNavigate();
  const onFinish = async (values: ILoginParams) => {
    console.log("Received values of form: ", values);

    const loginRes = await login(values).catch((error) => {
      console.log("error", error.message);
      // return Promise.resolve({
      //   token: "", // 登录失败，返回空字符串
      //   user: {}, // 登录失败，返回 null
      //   success: false, // 登录失败，返回 false
      //   message: error.message,
      // });
      message.error(error.message);
    });
    console.log("loginRes", loginRes);

    if (loginRes?.success) {
      message.success("登录成功");
      localStorage.setItem("token", loginRes.token);
      localStorage.setItem("userInfo", JSON.stringify(loginRes.user));
      // // 登录成功，跳转到首页
      navigate("/dashboard");
    }
    // else {
    //   message.error(loginRes.message);
    //   // 登录失败，提示错误信息
    // }
  };
  return (
    <div className="flex w-full h-[100vh]">
      <div className="flex-1 bg-amber-500 flex justify-center items-center">
        <h1 className=" text-white">写着玩 React + TypeScript + Vite</h1>
      </div>
      <div className="w-[500px] flex flex-col justify-center items-center">
        <h1 className="text-center text-2xl font-bold">欢迎回来</h1>
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          style={{ maxWidth: 400 }}
          autoComplete="off"
          onFinish={onFinish}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "请输入用户名！" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "请输入密码！" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
            <div className="flex justify-between items-center">
              <a href="/register">创建账号</a>
              <a href="/update-password">忘记密码</a>
            </div>
          </Form.Item>

          <Form.Item labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
            <Button className="w-full" type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
